const { app, BrowserWindow, systemPreferences, Menu, dialog, ipcMain } = require('electron')
const path = require('path')
const Store = require('electron-store');

const { autoUpdater } = require("electron-updater")
// const { createDataTable,db ,run ,getAll} = require("./db/sqlite3db.js")
Menu.setApplicationMenu(null)


function getParam() { 
    const param = {
        BIN_PATH: '',
        APP_PATH: '',
        TRTC_ENV: 'production'
    }
    const tmp = Array.from(process.argv)
    param.BIN_PATH = tmp[0]
    param.APP_PATH = tmp[1]
    tmp.forEach((value, index) => {
        if (index <= 1) return
        const splitValue = value.split('=')
        const key = splitValue[0].replace(/--/g, '').replace(/\s/g, '').toUpperCase()
        const val = splitValue[1].replace(/\s/g, '')
        if (typeof param[key] !== 'undefined') {
            param[key] = val
        }
    })
    return param
}
const param = getParam()
console.log('electron param:', param)
const portStart = 9527

let mainWindow = null
function gerServer() {
    return `http://localhost:${portStart}/404`
}

async function checkAndApplyDeviceAccessPrivilege() {
    const cameraPrivilege = systemPreferences.getMediaAccessStatus('camera')
    console.log(
        `checkAndApplyDeviceAccessPrivilege before apply cameraPrivilege: ${cameraPrivilege}`
    )
    if (cameraPrivilege !== 'granted') {
        await systemPreferences.askForMediaAccess('camera')
    }

    const micPrivilege = systemPreferences.getMediaAccessStatus('microphone')
    console.log(
        `checkAndApplyDeviceAccessPrivilege before apply micPrivilege: ${micPrivilege}`
    )
    if (micPrivilege !== 'granted') {
        await systemPreferences.askForMediaAccess('microphone')
    }

    const screenPrivilege = systemPreferences.getMediaAccessStatus('screen')
    console.log(
        `checkAndApplyDeviceAccessPrivilege before apply screenPrivilege: ${screenPrivilege}`
    )
}

async function createWindow() {
    Store.initRenderer();
  //  await checkAndApplyDeviceAccessPrivilege()
        // 创建浏览器窗口
    const win = new BrowserWindow({
        width: 1440,
        height: 900,
        minWidth: 1024,
        minHeight: 768,
        fullscreenable: true,
        fullscreen: true,
        simpleFullscreen: true,
        // resizable: false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.electron.js'),
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true
        }
    })



    // 在执行 npm run start 后，经常会窗口已经显示出来了，但代码还未构建好，
    // 此时捕获到 did-fail-load 事件，在之后延迟重载
    win.webContents.on('did-fail-load', function() {
        console.log(`createWindow: did-fail-load, reload ${param.TRTC_ENV} soon...`)
        setTimeout(() => {
            win.reload()
        }, 1000)
    })
    win.webContents.session.on('will-download', (event, item, webContents) => {
        console.log('will download')
        console.log(folderpath+`\\${item.getFilename()}`)
        //设置文件存放位置
      item.setSavePath(folderpath+`\\${item.getFilename()}`);
     
      item.on('updated', (event, state) => {
        if (state === 'interrupted') {
          console.log('Download is interrupted but can be resumed')
        } else if (state === 'progressing') {
          if (item.isPaused()) {
            console.log('Download is paused')
          } else {
            console.log(`Received bytes: ${item.getReceivedBytes()}`)
          }
        }
      })
      item.once('done', (event, state) => {
        if (state === 'completed') {
          console.log('Download successfully')
          const dialogOpts = {
                type: 'info',
                buttons: ['确定'],
                title: '下载完成',
                
            }

            dialog.showMessageBox(dialogOpts).then((returnValue) => {
                 
            })
        } else {
          console.log(`Download failed: ${state}`)
        }
      })
    })

    if (param.TRTC_ENV === 'production') {
        win.loadFile('dist/index.html')
        // win.webContents.openDevTools()
        checkForUpdates()
    } else {
        win.loadURL(gerServer())
        win.webContents.openDevTools()
    }
    
    mainWindow = win
      // 初始化数据库

   //   createDataTable();
}

app.whenReady().then(createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })

ipcMain.on('close-lj', (evt, arg) => {
    const dialogOpts = {
        type: 'info',
        buttons: ['退出','取消'],
        title: '提示',
        message: 
        '退出系统',
        detail: ``
    }

    dialog.showMessageBox(dialogOpts).then((returnValue) => {
        if (returnValue.response === 0) app.quit()
    })
})
let folderpath ="d:"
ipcMain.on('downloadVideo', (evt, args) => {
    downloadpath = args;
    // evt.sender.send('tips',downloadpath); 
    console.log('downloadVideo')     
    dialog.showOpenDialog({
        //默认路径
        defaultPath :'../',
        //选择操作，此处是打开文件夹
        properties: [
            'openDirectory',
        ],
        //过滤条件
        filters: [
            { name: 'All', extensions: ['*'] },
        ]
    }).then((res)=>{
        console.log(res)
        if(res.canceled){
            //取消了啊
        }else{
            folderpath = res.filePaths[0]
            console.log(folderpath)
            if(folderpath.endsWith("\\")){
                folderpath =  folderpath.substring(0,folderpath.lastIndexOf("\\"))
            }
            mainWindow.webContents.downloadURL(downloadpath);
        }
    }) 
    // mainWindow.webContents.downloadURL(downloadpath);
});

// 数据表创建

//ipcMain.on('database-query', (event, query, params) => {
    // getAll(query, params, (err, rows) => {
    //   if (err) {
    //     console.error('Query error:', err.message);
    //     event.reply('database-reply', { error: err.message });
    //   } else {
    //     event.reply('database-reply', { data: rows });
    //   }
    // });
//});
 // 执行查询
//  db.all('SELECT * FROM patrol_task', [], (err, rows) => {

//   });


//数据库赠删改 开始 

// ipcMain.on('run-database', (event, data) => {
//     console.log(data)
//     // run(data, [], (err, id) => {
//     //     console.log("uuuuu")
//     //     console.log(id)
//     // });
//     run(data, []).then(result=> {
//           event.reply('run-reply', { code: 200 ,id:result.id});
//     }).catch(error => {
//         // 处理操作失败的情况，error为发生的错误
//         event.reply('run-reply', { code: 500 });
//       });
//   });
 

//   ipcMain.on('query-database', (event, query) => {
//     all(query, []).then(result=> {
        
//         event.reply('run-reply', { code: 200 ,result});
//   }).catch(error => {
//       // 处理操作失败的情况，error为发生的错误
//       event.reply('run-reply', { code: 500 });
//     });
//   });








  



function checkForUpdates() {
    autoUpdater.on('checking-for-update', () => {})
    autoUpdater.on('update-available', (info) => {})
    autoUpdater.on('update-not-available', (info) => {})
    autoUpdater.on('error', (err) => {})
    autoUpdater.on('download-progress', (progressObj) => {
        let msg = "Download speed: " + progressObj.bytesPerSecond
        msg = msg + ' - Downloaded ' + progressObj.percent + '%'
        msg = msg + ' (' + progressObj.transferred + "/" + progressObj.total + ')'
    })
    autoUpdater.on('update-downloaded', (info) => {

        // The update will automatically be installed the next time the
        // app launches. If you want to, you can force the installation
        // now:
        const dialogOpts = {
            type: 'info',
            buttons: ['重启'],
            title: 'App Update',
            message: process.platform === 'win64' ? info.releaseNotes : info.releaseName,
            detail: `新版本 (${info.version}) 下载完成. Restart 重启应用.`
        }

        dialog.showMessageBox(dialogOpts).then((returnValue) => {
            if (returnValue.response === 0) autoUpdater.quitAndInstall()
        })
    })

    // More properties on autoUpdater, see https://www.electron.build/auto-update#AppUpdater
    //autoUpdater.autoDownload = true
    //autoUpdater.autoInstallOnAppQuit = true

    // No debugging! Check main.log for details.
    // Ready? Go!
    try {
        //autoUpdater.setFeedURL('')
        autoUpdater.checkForUpdates()
            //autoUpdater.checkForUpdatesAndNotify()
    } catch (error) {
        console.error(error)
    }
}